﻿<%@ WebHandler Language="C#" Class="FactoryStepPlanChartDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;
/**
 * Description: 分厂工序排产完成率看板(生产作业会)
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.6.16
 */

public class FactoryStepPlanChartDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//完成率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//完成率--明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportExcel":
                        getExportExcel(jObject);//完成率--导出
                        break;
                    case "getStepPlanRate":
                        r = getStepPlanRate(jObject);//排产率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getStepPlanRateDetail":
                        r = getStepPlanRateDetail(jObject);//排产率明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportStepPlanRateDetail":
                        getExportStepPlanRateDetail(jObject);//导出排产率明细
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getDataSql(JObject jObject)
    {
        JArray selectdate = JArray.Parse(jObject["selectdate"].ToString());
        string sql = @"
SELECT t.factoryid,t.factoryname,COUNT(t.rn) total,
       SUM(DECODE(t.status,'未完工',0,1)) finishqty,
       SUM(DECODE(t.status,'按时完工',1,0)) intimefinishqty,
       SUM(DECODE(t.status,'超期完工',1,0)) delayfinishqty,
       SUM(DECODE(t.status,'未完工',1,0)) notfinishqty,
       CASE WHEN COUNT(t.rn) = 0 THEN 100 ELSE ROUND(SUM(DECODE(t.status,'未完工',0,1))/COUNT(t.rn),4) * 100 END finishrate,
       CASE WHEN COUNT(t.rn) = 0 THEN 100 ELSE ROUND(SUM(DECODE(t.status,'按时完工',1,0))/COUNT(t.rn),4) * 100 END intimefinishrate,
       CASE WHEN COUNT(t.rn) = 0 THEN 100 ELSE ROUND(SUM(DECODE(t.status,'超期完工',1,0))/COUNT(t.rn),4) * 100 END delayfinishrate,
       CASE WHEN COUNT(t.rn) = 0 THEN 100 ELSE ROUND(SUM(DECODE(t.status,'未完工',1,0))/COUNT(t.rn),4) * 100 END notfinishrate  
FROM
(
    SELECT f.factoryid,t.factoryname,t.containername,t.specno sequence,t.workflowstepname,t.plannedfinishdate plandate,
       t.checkdate,
       DECODE(t.status,0,'未完工',1,'按时完工',2,'超期完工') status,
       rownum rn
    FROM r_containerstepplanboard t
    LEFT JOIN mes_factory_mapping@insitedb74 f ON f.factoryid = t.factoryid
    WHERE NVL(t.isuse,0) = 0 AND TRUNC(t.plannedfinishdate) >= to_date('{0}','yyyy-MM-dd') AND TRUNC(t.plannedfinishdate) <= to_date('{1}','yyyy-MM-dd') 
          AND t.factorycode IN ('600','601','607','608','609')
) t
GROUP BY t.factoryid,t.factoryname";
        sql = string.Format(sql, selectdate[0].ToString(), selectdate[1].ToString());
        return sql;
    }

    //查询
    Result getData(JObject jObject)
    {
        JArray arr = JArray.Parse(jObject["selectdate"].ToString());
        string sql = getDataSql(jObject);
        DataTable dt = dal.GetDataTable(sql, "MESDB17");
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getDetailSql(JObject jObject)
    {
        JArray arrSelectDate = JArray.Parse(jObject["selectdate"].ToString());
        string sql = @"
SELECT * 
FROM (
    SELECT f.factoryname,t.containername,t.specno sequence,t.workflowstepname,t.plannedfinishdate plandate,
           t.mfgordername,t.fromworkcentername,t.stepplancreatedate,
           t.checkdate,DECODE(t.status,0,'未完工',1,'按时完工',2,'超期完工') status
    FROM r_containerstepplanboard t
    LEFT JOIN mes_factory_mapping@insitedb74 f ON f.factoryid = t.factoryid
    WHERE NVL(t.isuse,0) = 0 AND TRUNC(t.plannedfinishdate) >= to_date('{0}','yyyy-MM-dd') AND TRUNC(t.plannedfinishdate) <= to_date('{1}','yyyy-MM-dd') 
          AND t.factoryname = '{2}'
) t";
        if (jObject["seriesName"].ToString() == "已完工数")
        {
            sql += " WHERE t.status in ('超期完工','按时完工') ";
        }
        else if (jObject["seriesName"].ToString() == "按时完工数")
        {
            sql += " WHERE t.status in ('按时完工') ";
        }
        else if (jObject["seriesName"].ToString() == "超期完工数")
        {
            sql += " WHERE t.status in ('超期完工') ";
        }
        if (jObject["seriesName"].ToString() == "未完工数")
        {
            sql += " WHERE t.status in ('未完工') ";
        }

        sql = string.Format(sql, arrSelectDate[0].ToString(), arrSelectDate[1].ToString(), jObject["factoryname"]);
        return sql;
    }

    Result getDetail(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"], "MESDB17");
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //排产率明细公用sql
    string getStepPlanRateDetailSql(JObject jObject)
    {
        JArray selectDate = JArray.Parse(jObject["selectdate"].ToString());
        string sql = @"
SELECT f.factoryname,cci.mfgordername,cci.containername,csd.workflowstepname,
       csp.stepplancreatedate,e.fullname,csp.plannedfinishdate,csd.reportdate,
       CASE WHEN csp.containerstepplanid IS NULL THEN '未排产' ELSE '已排产' END status 
FROM containersteprecord csd
INNER JOIN containercurrentinfo cci ON cci.containerid = csd.containerid
INNER JOIN mes_factory_mapping f ON f.factoryid = csd.factoryid
LEFT JOIN containerstepplan csp ON csp.containerid = csd.containerid AND csp.workflowstepname = csd.workflowstepname AND csp.plantype = 1
LEFT JOIN employee e ON e.employeeid = csp.stepplancreateemployeeid
WHERE cci.containerstatus = 1 AND f.factorycode IN ('601','609','607','600','608')
    AND csd.reportdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')
    AND csd.reportdate <= to_date('{1} 23:59:59','yyyy-MM-dd hh24:mi:ss') ";
        sql = string.Format(sql, selectDate[0].ToString(), selectDate[1].ToString());

        if (jObject["factoryname"] != null)
        {
            sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"].ToString());
        }

        return sql;
    }

    //排产率
    Result getStepPlanRate(JObject jObject)
    {
        string sql = @"
SELECT t.factoryname,COUNT(1) total,SUM(DECODE(t.status,'未排产',0,'已排产',1)) planqty,
       COUNT(1)-SUM(DECODE(t.status,'未排产',0,'已排产',1)) notplanqty,
       ROUND(SUM(DECODE(t.status,'未排产',0,'已排产',1)) / COUNT(1),4) * 100 planrate
FROM
(
  {0}
) t
GROUP BY t.factoryname";
        sql = string.Format(sql, getStepPlanRateDetailSql(jObject));
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //排产率明细
    Result getStepPlanRateDetail(JObject jObject)
    {
        string sql = getStepPlanRateDetailSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void getExportExcel(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        DataTable dt = dal.GetDataTable(sql, "MESDB17");
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["factoryname"].Caption = "主制分厂";
        dt.Columns["containername"].Caption = "流水卡号";
        dt.Columns["sequence"].Caption = "工序号";
        dt.Columns["workflowstepname"].Caption = "工序名称";
        dt.Columns["plandate"].Caption = "排产计划完成日期";
        dt.Columns["checkdate"].Caption = "完成时间";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["fromworkcentername"].Caption = "主制工区";
        dt.Columns["stepplancreatedate"].Caption = "排产时间";
        dt.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString());
    }

    //排产率明细导出
    void getExportStepPlanRateDetail(JObject jObject)
    {
        string sql = getStepPlanRateDetailSql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["factoryname"].Caption = "主制分厂";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["containername"].Caption = "流水卡号";
        dt.Columns["workflowstepname"].Caption = "工序名称";
        dt.Columns["stepplancreatedate"].Caption = "排产日期";
        dt.Columns["reportdate"].Caption = "报工时间";
        dt.Columns["fullname"].Caption = "排产人";
        dt.Columns["plannedfinishdate"].Caption = "排产要求完成日期";
        dt.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString());
    }
}